package com.sale.succ.datacomp.trade;

import static com.sale.succ.utils.TraderHelper.getLabel;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.sale.succ.components.MessDialog;
import com.sale.succ.objects.Session;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.Color;
import eve.ui.table.TableCellAttributes;
import eve.ui.table.TableModel;

;

public class TradeModel extends TableModel {

	private MessDialog loadingDialog;
	private HashMap trades;
	private HashMap row2Id;

	public TradeModel() {
		loadingDialog = new MessDialog(getLabel(TraderConstants.LOADING),
				MessDialog.NOB);
		loadingDialog.exec();

		try {
			initData();
		} finally {
			loadingDialog.close(0);
		}

		numRows = trades.size();
		numCols = 1;
		hasRowHeaders = false;
		hasColumnHeaders = false;
		fillToEqualWidths = true;

	}

	private void initData() {
		trades = ObjectsProvider.getInstance().getTradeMarkCollection();
		row2Id = new HashMap();
		Set ids = trades.keySet();
		Iterator it = ids.iterator();
		int i = 0;
		while (it.hasNext()) {
			row2Id.put(String.valueOf(i), it.next().toString());
			++i;
		}

	}

	/*
	 * public int search(String find) { int result = -1; find =
	 * find.toLowerCase().trim(); for (int i = 0; i < data.length; ++i) { String
	 * name = data[i];
	 * 
	 * if (name.toLowerCase().startsWith(find)) { result = i; break; } }
	 * 
	 * return result; }
	 */

	public int itemCount() {
		return trades.size();
	}

	public int calculateColWidth(int col) {
		if (col == -1)
			return 0;
		return super.calculateColWidth(col);
	}

	public int calculateRowHeight(int row) {
		if (row == -1)
			return 0;
		return 20;
	}

	public Object getCellData(int row, int col) {
		return trades.get(row2Id.get(String.valueOf(row)));
	}

	public String getMark(int row) {
		return (String) trades.get(row2Id.get(String.valueOf(row)));
	}

	public String getTradeId(int row) {
		return (String) row2Id.get(String.valueOf(row));
	}

	public TableCellAttributes getCellAttributes(int row, int col,
			boolean isSelected, TableCellAttributes ta) {
		ta = super.getCellAttributes(row, col, isSelected, ta);
		if (row != -1) {
			ta.clipCellData = true;
		}
		if (isSelected) {
			ta.foreground = Color.Black;
			ta.fillColor = TraderConstants.TBLMODEL_SELCOL;
		} else {
			if (row != -1) {
				String tradeId = (String) row2Id.get(String.valueOf(row));
				if (Session.getInstance().containsTradeMarkId(
						TraderHelper.convertToKey(Session.getInstance()
								.getClientId(), tradeId))
						&& row != -1) {
					ta.fillColor = Color.LightBlue;
				}

			}
			ta.foreground = Color.DarkGray;
			// ta.borderStyle = TableCellAttributes.BDR_NOBORDER;
		}
		return ta;
	}

}
